package com.itheima.admin.controller;

import com.itheima.pojo.dto.PageDto;
import com.itheima.pojo.vo.PageVo;
import com.itheima.pojo.vo.UserVo;
import com.itheima.pojo.dto.UserDto;
import com.itheima.pojo.dto.UserRoleDto;
import com.itheima.pojo.Config.Result;
import com.itheima.pojo.vo.UserPageVo;
import com.itheima.admin.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
@Api(value = "用户模块接口",tags = "admin_user",description = "用于实现后台用户的增删改查操作")
public class UserController {
    @Autowired
    private IUserService userService;

    @GetMapping("/{id}")
    @ApiOperation("根据id查询用户")
    public UserVo queryById(@PathVariable("id") String id){
        return userService.queryById(id);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("根据id删除用户")
    public Result deleteById(@PathVariable("id") String id){
        boolean flag=userService.deleteById(id);
        Result result = Result.builder()
                        .flag(flag)
                        .message(flag?"删除用户成功!":"删除用户失败")
                        .build();
        return result;
    }

    @PostMapping("/add")
    @ApiOperation("增加用户")
    public Result addUser(@RequestBody UserDto userDto, HttpSession session){
        boolean flag = userService.addUser(userDto,session);
        userDto.setUserId((String) session.getAttribute("userId"));
        Result result = Result.builder()
                        .flag(flag)
                        .data(userDto)
                        .message(flag?"添加用户成功!":"添加用户失败")
                        .build();
        return result;
    }

    @PostMapping("/list")
    @ApiOperation("分页查询用户列表数据")
    public PageVo<UserPageVo> queryByPage(@RequestBody PageDto pageDto) {
        if (pageDto.getCurrentPage() == null) {
            pageDto.setCurrentPage(1);
        }
        if (pageDto.getPageSize() == null) {
            pageDto.setPageSize(10);
        }
        return userService.queryByPage(pageDto);
    }

    @PutMapping("/dept/edit")
    @ApiOperation("根据id修改用户")
    public Result updateUser(@RequestBody UserDto userDto){
        boolean flag=userService.updateUser(userDto);

        Result result=Result.builder()
                    .flag(flag)
                    .data(userDto)
                    .message(flag?"修改用户成功!":"修改用户失败!")
                    .build();
        return result;
    }

    @PostMapping("/role")
    @ApiOperation("用户授权")
    public Result addUserRole(@RequestBody UserRoleDto userRoleDto){
        boolean flag=userService.addUserRole(userRoleDto);

        Result result=Result.builder()
                .flag(flag)
                .message(flag?"修改用户成功!":"修改用户失败!")
                .build();
        return result;
    }
}
